package com.distributed.tcp.manager;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanNotOfRequiredTypeException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

/**
 * 消息处理器工厂
 */
@Component
@Slf4j
public class MessageHandlerFactory {
    private final ApplicationContext applicationContext;
    private final MessageHandler messageHandler;

    @Autowired
    public MessageHandlerFactory(ApplicationContext applicationContext, 
                                @Autowired(required = false) MessageExecuteHandler messageHandler) {
        this.applicationContext = applicationContext;
        this.messageHandler = messageHandler != null ? messageHandler : new MessageExecuteHandler();
    }

    /**
     * 获取指定类型的消息处理器
     */
    public MessageHandler getHandler(String handlerType) {
        if (handlerType == null || handlerType.isEmpty()) {
            return messageHandler;
        }
        try {
            return applicationContext.getBean(handlerType, MessageHandler.class);
        } catch (NoSuchBeanDefinitionException e) { // 只捕获特定异常
            log.warn("未找到类型为{}的MessageHandler，使用默认处理器", handlerType);
            return messageHandler;
        } catch (BeanNotOfRequiredTypeException e) {
            log.error("Bean {} 不是MessageHandler类型", handlerType, e);
            return messageHandler;
        }
    }
}
